package com.david.cloud.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.david.cloud.service.CodeService;
import com.david.cloud.user.entity.Token;
import com.david.cloud.user.entity.User;
import com.david.cloud.user.mapper.UserMapper;
import com.david.cloud.user.service.ITokenService;
import com.david.cloud.user.service.IUserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author david
 * @since 2020-05-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Reference
    private CodeService codeService;
    @Autowired
    private ITokenService tokenService;

    @Override
    public User register(String email, String password, String code) {
        Integer validate = codeService.validate(email, code);
        if (validate == 0) {
            User user = new User();
            user.setName(email);
            user.setEmail(email);
            user.setPassword(password);
            save(user);
            genToken(email, user);
            return user;
        } else {
            throw new RuntimeException("验证码失效");
        }
    }


    @Transactional
    @Override
    public User login(String email, String password) {
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getEmail, email).eq(User::getPassword, password));
        if (user == null) {
            throw new RuntimeException("用户密码错误");
        } else {
            genToken(email, user);
            return user;
        }
    }

    private void genToken(String email, User user) {
        Token token = tokenService.genToken(email);
        user.setToken(token);
    }
}
